//
//  CCUserLoginVC.swift
//  swift_weibo
//
//  Created by ccl on 16/3/1.
//  Copyright © 2016年 LittleBoy. All rights reserved.
//

import UIKit
import SVProgressHUD

class CCUserLoginVC: UIViewController, UIWebViewDelegate {
   
    private let  App_Key = "781049584";
    private let  App_Secret = "a346577954e6bdf0df8e71b2101457d7";
    private let  App_Url = "http://www.baidu.com";
    
    // 替换view 为WebView,  设置title, 和导航栏
    
    lazy var webView : UIWebView = {
        let web = UIWebView();
        web.delegate = self;
        return web;
    }()
    
    override func loadView() {
        
        view = webView;
        title = "微博登录";
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close");
    }
    
   
    
    override func viewDidDisappear(animated: Bool) {
        SVProgressHUD.dismiss();
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // 加载web登录页
        loadUserLoginWeb();
    }
    
    //关闭页面
    func close(){
        
        dismissViewControllerAnimated(true, completion: nil );
    }
    // 加载web登录页
    func loadUserLoginWeb() {
        
      let URLStr =  "https://api.weibo.com/oauth2/authorize?client_id=\(App_Key)&redirect_uri=\(App_Url)";
        let URL = NSURL(string: URLStr)!;
        let webView = view as! UIWebView;
        
        let request = NSURLRequest(URL: URL);
        webView.loadRequest(request);
    }
    
   //获取token
    func loadUserToken(code : String){
       
        let URLStr = "https://api.weibo.com/oauth2/access_token";
        let parmas = ["client_id" : App_Key , "client_secret" : App_Secret,"grant_type" : "authorization_code","code" : code,"redirect_uri" : App_Url];
    
     CCNetWorkingTooks.shareNetWorkingTook().POST(URLStr, parameters: parmas, progress: nil, success: { (_, json) -> Void in
       // 成功
        let account =  CCUserAccountToken(dic: json as! [String : AnyObject]);
        
        account.saveAccount();
        account.loadUserInfo({ (account, error) -> () in
           
            if account != nil {
             // 获取用户信息成功
                shareUserAccount = account;
                
              UIApplication.sharedApplication().keyWindow?.rootViewController = CCWelcomeVC();
                
            }else{
             // 获取用户信息失败
                SVProgressHUD.showErrorWithStatus("网络连接失败");
              
            }
            
        })
        SVProgressHUD.showSuccessWithStatus("登录成功");
        
        }) { (_ , error ) -> Void in
         // 失败
            SVProgressHUD.showErrorWithStatus("网络连接失败");

        };
    }
    
    // MARK: webView代理
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
       
        let UrlStr = request.URL?.absoluteString;
        
        if UrlStr!.hasPrefix(App_Url){
         //包含回调地址
            //取code
            let query = request.URL!.query;
            let codeStr = "code=";
            let code = query?.substringFromIndex(codeStr.endIndex);
            loadUserToken(code!);
            // 是回调的web, 不加载
            return false;
        }
        // 是微博的web加载
        return true;
    }

    func webViewDidStartLoad(webView: UIWebView){
        SVProgressHUD.show();
    
    }
    
    func webViewDidFinishLoad(webView: UIWebView){
        SVProgressHUD.dismiss();
    
    }
    
  
    
}
